package com.funtl.screw.common.security.service;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.funtl.screw.admin.entity.SysUser;
import com.funtl.screw.admin.vo.UserInfoVo;
import com.funtl.screw.common.core.constant.CommonConstants;
import com.funtl.screw.common.core.constant.SecurityConstants;
import com.funtl.screw.common.core.util.ResponseResult;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * UserDetailsService 扩展
 *
 * @author Lusifer
 */
public interface ServiceUserDetailsService extends UserDetailsService {

    default UserDetails getUserDetails(ResponseResult<UserInfoVo> result) {
        if (result == null || result.getData() == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        UserInfoVo info = result.getData();
        Set<String> dbAuthsSet = new HashSet<>();
        if (ArrayUtil.isNotEmpty(info.getRoles())) {
            // 获取角色
            Arrays.stream(info.getRoles()).forEach(roleId -> dbAuthsSet.add(SecurityConstants.ROLE + roleId));
            // 获取资源
            dbAuthsSet.addAll(Arrays.asList(info.getPermissions()));
        }
        Collection<? extends GrantedAuthority> authorities = AuthorityUtils
                .createAuthorityList(dbAuthsSet.toArray(new String[0]));
        SysUser user = info.getSysUser();
        boolean enabled = StrUtil.equals(user.getLockFlag(), CommonConstants.STATUS_NORMAL);
        // 构造security用户
        return new ServiceUser(user.getUserId(), user.getDeptId(), user.getPhone(), user.getAvatar(),
                user.getUsername(), SecurityConstants.BCRYPT + user.getPassword(), enabled, true, true,
                !CommonConstants.STATUS_LOCK.equals(user.getLockFlag()), authorities);
    }

    /**
     * 根据手机号登录
     *
     * @param code mobile
     * @return UserDetails
     */
    UserDetails loadUserBySocial(String code) throws UsernameNotFoundException;

}
